package com.sjtu.bookread;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import androidx.core.content.ContextCompat;
import com.sjtu.bookread.control.DatabaseControl;
import com.sjtu.bookread.obj.BookObj;
import com.sjtu.bookread.obj.BookObj1;
import com.sjtu.bookread.obj.CategoryObj;
import com.sjtu.bookread.obj.ChapterLinkObj;
import com.sjtu.bookread.obj.RecomListObj;
import com.sjtu.bookread.obj.ShelfBookObj;
import com.sjtu.bookread.service.BookService;
import com.sjtu.bookread.service.RecomService;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import per.wsj.library.AndRatingBar;

import static com.sjtu.bookread.MainActivity.az;
import static com.sjtu.bookread.MainActivity.myBooks;

public class BookDetailActivity extends AppCompatActivity {
    RadioButton addButton;
    RadioButton readButton;
    //    RadioButton downloadButton;

    ImageView back;
    TextView pageTitle;
    ImageView bookCover;
    TextView bookTitle;
    TextView bookInfo;
    AndRatingBar ratingBar;
    TextView bookIntro;

    // 书籍对象
    private BookObj1 bookObj;

    private Bitmap cover;

    Handler mHandler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        changeStatusIconCollor(true);
        Window window =this.getWindow();
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(ContextCompat.getColor(this,R.color.colorGreyTitle));

        setContentView(R.layout.activity_book_detail);

        // 获取控件
        back = findViewById(R.id.detail_back);
        pageTitle = findViewById(R.id.detail_title);
        addButton = findViewById(R.id.detail_bottom_add);
        readButton = findViewById(R.id.detail_bottom_read);
//        downloadButton = findViewById(R.id.detail_bottom_download);
        bookCover = findViewById(R.id.detail_cover);
        bookTitle = findViewById(R.id.detail_bookTitle);
        bookInfo = findViewById(R.id.detail_TV);
        ratingBar = findViewById(R.id.Rating_bar);
        bookIntro = findViewById(R.id.detail_longIntro);


        Intent intent = getIntent();
        final Bundle bundle = intent.getExtras();
        bookObj = (BookObj1)bundle.getSerializable("bookobj");

        // 获取封面图片
        final String iconURL = RecomService.ApiUrl + "/" + bookObj.getCover();
        final Matrix largeMatrix = new Matrix();
        final Matrix littleMatrix = new Matrix();
        largeMatrix.postScale((float)2, (float)2);
        littleMatrix.postScale((float)0.4, (float)0.4);
        if (!isNetWorkConnected(BookDetailActivity.this)) {
            Toast.makeText(BookDetailActivity.this, "未连接网络", Toast.LENGTH_SHORT).show();
        } else {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        URL url = new URL(iconURL);
                        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                        connection.setRequestMethod("GET");
                        connection.setConnectTimeout(10000);
                        if (connection.getResponseCode() == 200) {
                            InputStream inputStream = connection.getInputStream();
                            cover = BitmapFactory.decodeStream(inputStream);
                            if (cover != null) {
                                mHandler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        Log.d("width", String.valueOf(cover.getWidth()));
                                        Log.d("height", String.valueOf(cover.getHeight()));
                                /*if (cover.getWidth() <= 150 && cover.getHeight() <= 200) {
                                    bookCover.setImageBitmap(Bitmap.createBitmap(cover, 0, 0, cover.getWidth(), cover.getHeight(), largeMatrix, true));
                                } else if (cover.getWidth() > 300 && cover.getHeight() > 400) {
                                    bookCover.setImageBitmap(Bitmap.createBitmap(cover, 0, 0, cover.getWidth(), cover.getHeight(), littleMatrix, true));
                                } else {
                                    bookCover.setImageBitmap(cover);
                                }*/
                                        bookCover.setImageBitmap(cover);
                                    }
                                });
                            }
                        }
                    } catch (Exception e) {
                        System.err.println(e.getMessage());
                    }
                }
            }).start();
        }

        if (!isNetWorkConnected(BookDetailActivity.this)) {
            Toast.makeText(BookDetailActivity.this, "未连接网络", Toast.LENGTH_SHORT).show();
        } else {
            // 获取书籍相关信息
            new Thread(new Runnable() {
                @Override
                public void run() {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            bookTitle.setText(bookObj.getTitle());
                            bookInfo.setText(bookObj.getAuthor() + " | " + bookObj.getCate());
                            String updateStr = "";
                            // int followerNum = bookObj.getLatelyFollower() / 10000;
                            String intro = bookObj.getShortIntro();
                            bookIntro.setText(intro);
                        }
                    });
                }
            }).start();
        }


        ratingBar.setOnRatingChangeListener(new AndRatingBar.OnRatingChangeListener() {
            @Override
            public void onRatingChanged(AndRatingBar ratingBar, final float rating) {
                //获取星星数量
                int num = ratingBar.getNumStars();
                //获取步长
                float step = ratingBar.getStepSize();
                //获取当前评分,与参数rating一致
                // float currentRating = ratingBar.getRating();

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Log.d("submit_rate",String.valueOf((int)rating));
                        RecomService.getRecomService().submit_rate(bookObj.getId(),(int)rating, MainActivity.ax, MainActivity.ay, MainActivity.az);
                    }
                }).start();
            }
        });

        // 返回
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        if (judge_exist(bookObj.getId())) {
            // 已存在
            setButtonToDelete();
        } else {
            // 不存在
            setButtonToAdd();
        }

        // 阅读
        readButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(BookDetailActivity.this, ReadPageActivity1.class);
                Bundle bundle = new Bundle();
                bundle.putInt("bookid", bookObj.getId());
                bundle.putString("bookname",bookObj.getTitle());
                intent.putExtras(bundle);

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Log.d("submit_inreader","11111111111111111111");
                        RecomService.getRecomService().submit_in_reader(bookObj.getId(),MainActivity.ax, MainActivity.ay,MainActivity.az);
                    }
                }).start();

                startActivity(intent);
            }
        });

        // 下载
        /*downloadButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                *//*new Thread(new Runnable() {
                    @Override
                    public void run() {
                        for (int i = 0; i < linkList.size(); i++) {
                            ChapterObj chapterObj = BookService.getBookService().getChapterByLink(linkList.get(i).getLink());
                            stringBuilder.append(chapterObj.getIchapter().getTitle());
                            stringBuilder.append("\n");
                            stringBuilder.append(chapterObj.getIchapter().getBody());
                        }

                    }
                }).start();*//*
                Toast.makeText(BookDetailActivity.this, "功能开发中，敬请期待", Toast.LENGTH_SHORT).show();
            }
        });*/

        // 分享
        (findViewById(R.id.detail_share)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String strToShare = "[图书分享] 我给你分享了 "+bookObj.getTitle()+" 这本书\n";
                strToShare += bookObj.getShortIntro()+"\n";
                strToShare += "这本书是"+bookObj.getAuthor()+"写的，快把这条信息复制到阅读搜索框中看一看吧！\n";
                strToShare += "<--|" + bookObj.getId() + "|-->";

                Intent intent = new Intent(Intent.ACTION_SEND);
                intent.setType("text/plain");
                intent.putExtra(Intent.EXTRA_TEXT, strToShare);
                startActivity(intent);
            }
        });
    }

    private void setButtonToAdd() {
        addButton.setText("加入书架");
        addButton.setTextColor(getResources().getColor(R.color.colorRed));
        addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(BookDetailActivity.this, "已添加《" + bookObj.getTitle() + "》", Toast.LENGTH_SHORT).show();
                setButtonToDelete();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        RecomService.getRecomService().adddelShelfbook(1,bookObj.getId());
                    }
                }).start();
            }
        });
    }

    public void changeStatusIconCollor(boolean setDark) {
        View decorView = getWindow().getDecorView();
        if(decorView != null){
            int vis = decorView.getSystemUiVisibility();
            if(setDark){
                vis |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
            } else{
                vis &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
            }
            decorView.setSystemUiVisibility(vis);
        }
    }

    private void setButtonToDelete() {
        addButton.setText("移除书架");
        addButton.setTextColor(getResources().getColor(R.color.colorGrey));
        addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(BookDetailActivity.this, "已移除《" + bookObj.getTitle() + "》", Toast.LENGTH_SHORT).show();
                setButtonToAdd();

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        RecomService.getRecomService().adddelShelfbook(0,bookObj.getId());
                    }
                }).start();
            }
        });
    }

    // 辅助函数：判断网络是否连接
    private boolean isNetWorkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isConnected();
            }
        }
        return false;
    }

    private boolean judge_exist(int id) {
        for (BookObj1 bookObj1 : myBooks) {
            if (bookObj1.getId() == id)
                return true;
        }
        return false;
    }

}
